package cn.xiaopengstack.types.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * @author jiangyangang
 */
@AllArgsConstructor
@Getter
public enum RedisLuaScriptEnum {
    trade_team_occupy_lua("""
                    --- 参数列表
                    local teamStockKey = KEYS[1]
                    local recoveryTeamStockKey = KEYS[2]
                    local stockSegmentLockKey = KEYS[3]
                    local targetCountStr = ARGV[1]
                    local validTimeStr = ARGV[2]
                    
                    local function safe_tonumber(value)
                        if type(value) == 'number' then
                            return value
                        elseif type(value) == 'string' then
                            return tonumber(value)
                        else
                            return tonumber(tostring(value))
                        end
                    end
                    
                    local targetCount = safe_tonumber(targetCountStr)
                    local validTime = safe_tonumber(validTimeStr)

                    --- 获取恢复量
                    local recoveryTeamStockCount = redis.call("get", recoveryTeamStockKey)

                    if recoveryTeamStockCount == false then
                        recoveryTeamStockCount = 0
                    else
                        recoveryTeamStockCount = tonumber(recoveryTeamStockCount)
                    end

                    --- 递增库存
                    local occupyCount = redis.call("incr", teamStockKey)
                    redis.call("expire", teamStockKey, (validTime + 60) * 60000)
                    --- 判断超卖
                    if occupyCount > targetCount + recoveryTeamStockCount then
                        redis.call("set", teamStockKey, targetCount)
                        return -1
                    end

                    stockSegmentLockKey = stockSegmentLockKey ..  tostring(occupyCount)

                    --- 设置兜底分段锁，有效期为validTime + 60分钟
                    local localResult = redis.call("setnx", stockSegmentLockKey, "lock")
                    if localResult == 1 then
                        --- 加锁成功，设置过期时间
                        redis.call("expire", stockSegmentLockKey, (validTime + 60) * 60000)
                        return 1
                    else
                        return 0
                    end
                    """, "锁单库存扣减"),

    trade_team_stock_refund_lua("""
            local teamStockKey = KEYS[1]
            --- 获取库存内容
            local stock = redis.call("get", teamStockKey)
            if (stock == nil) then
                return -1
            elseif (tonumber(stock) <= 0) then
                return -1
            else
                return redis.call("decr", teamStockKey)
            end
            """, "锁单库存回退")
    ;
    private final String script;

    private final String desc;


}
